from google.appengine.dist import use_library
use_library('django', '1.2')

from google.appengine.ext.webapp import template
from google.appengine.ext import webapp
from google.appengine.ext.webapp.util import run_wsgi_app
import facebookconnect as fc
from model import Score, User

_FbApiKey = 'ea1ddc46c2f43e189ce0f9b35c393cc3'
_FbSecret = 'ad9b2c09e5fbe10645195a14d5f38e22'
_CanvasURL = 'facebookgameserver.appspot.com/'
_CanvasPage = 'https://apps.facebook.com/facutest/'
_AppID = '137618472977406'


class MainPage(fc.BaseHandler):
    def get(self):
        if self.user:
            self.response.out.write("hola "+str(self.user.name)+"!<br />")
            sco = Score.all()
            sco.filter("user_id =",self.user.user_id)
            sco.filter("game_id =","1")
            puntos = 0
            res=sco.fetch(1)
            if res:
                puntos = res[0].score
            else:
                s = Score(user_id = self.user.user_id,
                            game_id = "1",
                            score = 0)
                s.put()
            self.response.out.write("tenes "+str(puntos)+" puntos!<br />")
            self.response.out.write("<a href='darpunto'>dame un punto!</a><br />")
            self.response.out.write("<a href='scores'>ver puntos</a><br />")
            
        else:
            url = 'https://www.facebook.com/dialog/oauth?client_id=' + _AppID + '&redirect_uri='+_CanvasPage
            self.response.out.write('<script language="javascript">top.location.href="' + url + '"</script>')

class DarPunto(fc.BaseHandler):
    def get(self):
        sco = Score.all()
        sco.filter("user_id =",self.user.user_id)
        sco.filter("game_id =","1")
        res=sco.fetch(1)
        if res:
            puntos = res[0].score
        else:
            s = Score(user_id = self.user.user_id,
                        game_id = "1",
                        score=0
                        )
            s.put()
        res[0].score+=1
        Score.put(res[0])
        
        self.redirect("/")

class ShowScores(fc.BaseHandler):
    def get(self):
        self.response.out.write("Puntos:<br />")
        for i in User.all().fetch(100):
            sco = Score.all()
            sco.filter('user_id', i.user_id)
            sco.filter("game_id =", "1")
            res = sco.fetch(1)
            if res:
                s = res[0].score
            else:
                s=0
            self.response.out.write(i.name + ": " + str(s) + "<br />")

def main():
    application = webapp.WSGIApplication([('/', MainPage),('/darpunto',DarPunto),('/scores',ShowScores)],
                                         debug=True)
    run_wsgi_app(application)

if __name__ == "__main__":
    main()







